const user = require('../models/user')
const User = new user()
// 注册
function register(req, res) {
  let body = { ...req.body }
  console.log('body', req.body)
  if (!body.name) {
    res.json({ code: 203, message: "姓名不能为空" })
    return false
  }
  if (!body.password) {
    res.json({ code: 203, message: "密码不能为空" })
    return false
  }

  let data = User.addUser(body)
  // console.log(data)
  if (data.message) return res.json({ code: 204, data })
  res.json({ code: 200, data })
}
// 登录
function login(req, res) {
  let { name, password } = { ...req.body }
  console.log({ name, password })
  let data = User.getUser({ name, password })
  console.log(data)
  if (data.message || data.length === 0) {
    res.json({ code: 203, message: "登录失败，用户名或者密码不正确" })
    return false
  }
  res.json({ code: 200, message: "登录成功", token: "14312jhnqjrqruqbr532q5hrr" })
}

// 获取用户信息
function getUserInfo(req, res) {
  console.log(req.params)
  // console.log(req.query)
  let queryData = { ...req.params }
  console.log(queryData)
  // if (req.params.id === "1") res.json({ code: 200, data: { name: "李梅", sex: "女", age: "19", loving: "打羽毛球", desc: "单身" } })
  // else res.json({ code: 404, message: "查询的用户不存在" })
  let data = User.getUser(queryData)
  if (data.message || data.length === 0) return res.json({ code: 404, message: "查询的用户不存在" })
  res.json({ code: 200, data })
}

// 修改用户信息
function editUserInfo(req, res) {
  let id = req.params.id
  console.log(id)
  let editData = {...req.body, id}
  console.log('body', req.body)
  if (!editData.name) {
    res.json({ code: 203, message: "姓名不能为空" })
    return false
  }
  if (!editData.password) {
    res.json({ code: 203, message: "密码不能为空" })
    return false
  }
  if (editData.password.length < 6) {
    res.json({ code: 203, message: "密码不能少于6位" })
    return false
  }
  let data = User.editUser(editData)
  // console.log(data)
  if (data.message) return res.json({ code: 204, data })
  res.json({ code: 200, data })
}
// 删除用户
function deleteUser(req, res) {
let data = User.deleteUser(req.params.id)
res.json({ code: 200, data })
}

module.exports = {
  register,
  login,
  getUserInfo,
  editUserInfo,
  deleteUser
}
